package kn.pulldata.mq;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import kn.pulldata.common.RabbitMqCon;
import kn.pulldata.req.InfoPushData;
import kn.pulldata.service.ExternalService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Objects;

@Component
@Slf4j
public class PushConsumer {

    @Autowired
    private ExternalService externalService;



    @RabbitListener(queues = RabbitMqCon.WUDAOGANG_QUEUE,containerFactory = "factory1")
    public void keywordReceiveMessage(String message, Channel channel, Message rabbitMessage) {

        try {
            InfoPushData infoPushData = JSONObject.parseObject(message, InfoPushData.class);
            if(Objects.isNull(infoPushData)){
                channel.basicAck(rabbitMessage.getMessageProperties().getDeliveryTag(), false);
                return;
            }

            externalService.pushWebSocket(infoPushData);

            channel.basicAck(rabbitMessage.getMessageProperties().getDeliveryTag(), false);

        }
        catch (JSONException jsonException){
            log.error("json解析异常，消息: {}" ,JSONUtil.toJsonStr(message));
        }catch (Exception e) {
            e.printStackTrace();
            try {
                int retryCount = (int) rabbitMessage.getMessageProperties().getHeaders().getOrDefault("x-death", 0);
                if (retryCount > 5) {
                    // 重试次数超过阈值，选择丢弃
                    channel.basicNack(rabbitMessage.getMessageProperties().getDeliveryTag(), false, false);
                    log.error("消息推送数据重试次数超过阈值，丢弃消息: {}" + rabbitMessage.getMessageProperties().getMessageId());
                } else {
                    // 否则继续重试
                    channel.basicNack(rabbitMessage.getMessageProperties().getDeliveryTag(), false, true);
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

}
